package math
{
	
	import flash.display.DisplayObject;
	import flash.display.Graphics;
	import flash.display.Sprite;
	import flash.events.*;
	import flash.geom.*;
	
	import kim.math.ui.Ball;
	import kim.math.ui.Photo;
	
	public class Sphere2 extends Sprite
	{
		
		private var R:int=240;//球体半径
		private var container:Sprite=new Sprite();//创建容器
		private var angle:Number=30*Math.PI/180;
		private var list:Array=new Array();
		
		private var photoCount:Array=[1,6,10,12,10,6,1];//图片数目		
		private var angleX:Array=[90,60,30,0,-30,-60,-90];//倾斜的x值
		private var angleY:Array=[0,60,36,30,36,60,0];//倾斜的y值
		
		private var speedx:Number=0;
		private var speedy:Number=0;
		
		public function Sphere2(centerX:Number, centerY:Number, _stage:DisplayObject)
		{
			addChild(container);
			container.x=centerX;
			container.y=centerY;
			container.z=0;
			createSphere();//创建球体分布
			addEventListener(Event.ENTER_FRAME,Run);
			_stage.addEventListener(MouseEvent.MOUSE_MOVE,onMove);
		}
		
		private function createSphere():void
		{
			for (var i:int=0; i<7; i++)
			{ 
				for (var j:int=0; j<photoCount[i]; j++)
				{
					
					var ball:Photo=new Photo();
					container.addChild(ball);
					list.push(ball);
					ball.x=R*Math.sin(i*angle)*Math.cos(j*angleY[i]*Math.PI/180);//球体公式表现
					ball.z=R*Math.sin(i*angle)*Math.sin(j*angleY[i]*Math.PI/180);
					ball.y=R*Math.cos(i*angle);
					ball.rotationX= angleX[i];//偏移角度计算
					ball.rotationY=-j*angleY[i]+270;//
					
				}
			}
			
		}
		//鼠标交互
		private function onMove(event:MouseEvent):void
		{
			speedx=(mouseX-container.x)*0.01;
			speedy=(mouseY-container.y)*0.01;
			
		}
		
		private function Run(event:Event):void
		{
			container.rotationY+=speedx;
			container.rotationX+=speedy;
			sortZ();
		}
		
		//深度排序管理
		private function sortZ():void
		{
			list.sort(depthSort);
			
			for (var i:int=0; i<list.length; i++)
			{
				var myimage:Photo=list[i];
				container.setChildIndex(myimage,i);
				
			}
			
		}
		
		private function depthSort(objA:DisplayObject,objB:DisplayObject):int
		{
			var posA:Vector3D=objA.transform.matrix3D.position;
			posA=container.transform.matrix3D.deltaTransformVector(posA);
			
			var posB:Vector3D=objB.transform.matrix3D.position;
			posB=container.transform.matrix3D.deltaTransformVector(posB);
			return posB.z-posA.z;
		}
		
	}
}